package com.boe.csb.core.service.csb;

import com.alibaba.csb.console.sdk.Result;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.boe.csb.core.common.utils.CsbApiCaller;
import com.boe.csb.core.common.utils.GsonUtils;
import com.boe.csb.core.entity.po.BoeUser;
import com.boe.csb.core.service.user.BoeUserService;
import com.google.gson.JsonObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by tianjin.lp on 16/11/22.
 */
@Service("csbUserService")
public class CsbUserService {


    @Autowired
    private CsbManagerApiService csbManagerApiService;
    @Autowired
    private CsbManagerOrderService csbManagerOrderService;
    @Autowired
    private BoeUserService boeUserService;

    private static final String DELETE_CSB_USER = "/api/admin/user/delete";

    private static final String AUTO_APPROVE_USER = "true";


    /**
     * 根据ID获取用户信息
     */
    public String getUserInfoByUserId(String userId) {
        Map<String, String> userInfoMap = new HashMap<String, String>();
        userInfoMap.put("userId", userId);
        Result result = CsbApiCaller.callCsbGetApi("/api/admin/user/info", userInfoMap);
        return result.getData().toString();
    }


    /**
     * 创建用户
     *
     * @param userId boeUserId
     */
    public Result createCSBUser(String adminId, String userId, String password,String loginId, boolean isAdmin) {
        String createCsbUserAPI = "api/admin/user/create";
        Map<String, String> map = new HashMap<>();
        map.put("userId", adminId);
        map.put("autoApproveUser", AUTO_APPROVE_USER);//直接通过用户审批
        map.put("password", password);

        JSONObject data = new JSONObject();
        data.put("userId", userId);
        data.put("loginId",loginId);
        data.put("isAdmin", isAdmin);

        Result result = CsbApiCaller.callCsbPostApi(createCsbUserAPI, map, JSON.toJSONString(data));
        if (result.isSuccess()) {
            //非admin才会创建服务组
            if(!isAdmin){
                //创建凭证
                csbManagerOrderService.createCredential(userId);
                //创建服务组
                csbManagerApiService.createProject(userId);
            }
        }
        return result;
    }


    /**
     * 删除用户
     */
    public Result deleteCSBUser(String userId) {
        Map<String, String> map = new HashMap<>();
        map.put("userId", userId);
        return CsbApiCaller.callCsbPostApi(DELETE_CSB_USER, map, "");
    }


}
